package com.zcy;

import com.espertech.esper.common.client.EventBean;
import com.espertech.esper.runtime.client.EPEventService;
import com.zcy.event.MyEvent;
import com.zcy.util.EsperBuilder;
import com.zcy.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;

/**
 * 14.3.22。生存时间窗口（timetolive或ext:timetolive）
 * <p>
 * 事件到达时，运行时将评估时间戳记表达式并获取长型时间戳记。运行时将该时间戳记值与运行时时间进行比较：
 * <p>
 * 如果时间戳早于运行时间或与运行时间相同，则运行时会立即将事件释放到删除流中，并且根本不会保留该事件。
 * 如果时间戳值比运行时间新，则数据窗口将保留该事件，直到运行时间向前移动，以使时间戳等于或早于运行时间。
 */
@Slf4j
public class TimeToLiveWindow extends TimeUtils {

    private static final String _TimeToLiveWindow = "@name('time-order-window') select rstream sum(num) from MyEvent#timetolive(timestamp)";

    /**
     * TODO 没有试验出来
     */
    @Test
    public void sortWinTest() {
        EsperBuilder esperBuilder = new EsperBuilder(_TimeToLiveWindow, new Class[]{MyEvent.class});

        esperBuilder.startCompile();

        EPEventService epEventService = esperBuilder.startDeploy((eventBeans, eventBeans1, epStatement, epRuntime) -> {
            for (int i = 0; i < eventBeans.length; i++) {
                EventBean eventBean = eventBeans[i];
                log.info("sum is : {}", eventBean.get("sum(num)"));
            }
        });

        epEventService.sendEventBean(MyEvent.builder().timestamp(1620376321).amount("001").name("001-name").num(10).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 3L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(1620376810).amount("001").name("001-name").num(20).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 1L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(1620376813).amount("001").name("001-name").num(30).build(), MyEvent.class.getSimpleName());

        sleep(TimeUnit.SECONDS, 40L);
    }


}
